import { ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import MarkdownIt from 'markdown-it'
import { renderAsync } from 'docx-preview'
import {
  IconFile,
  IconImage,
  IconMusic,
  IconPlayCircle,
  IconFile as IconFileWord,
  IconFile as IconFileExcel,
  IconFile as IconFilePdf,
  IconFile as IconFileZip,
  IconCode,
  IconFile as IconFileText
} from '@arco-design/web-vue/es/icon'

const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true
})

export function useFilePreview() {
  const previewVisible = ref(false)
  const previewFile = ref<any>(null)
  const markdownContent = ref('')
  const previewType = ref<'image' | 'pdf' | 'text' | 'office' | 'markdown' | 'other'>('other')

  // 获取文件类型
  const getFileType = (extension: string | undefined) => {
    if (!extension) return 'other'

    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension)) {
      return 'image'
    }
    if (extension === 'pdf') {
      return 'pdf'
    }
    if (extension === 'md') {
      return 'markdown'
    }
    if (['txt', 'json', 'xml', 'log'].includes(extension)) {
      return 'text'
    }
    if (['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(extension)) {
      return 'office'
    }
    return 'other'
  }

  // 获取文件图标
  const getFileIcon = (fileName: string) => {
    const extension = fileName.split('.').pop()?.toLowerCase()

    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension || '')) {
      return IconImage
    }
    if (['mp3', 'wav', 'ogg', 'flac', 'm4a'].includes(extension || '')) {
      return IconMusic
    }
    if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'].includes(extension || '')) {
      return IconPlayCircle
    }
    if (['doc', 'docx'].includes(extension || '')) {
      return IconFileWord
    }
    if (['xls', 'xlsx'].includes(extension || '')) {
      return IconFileExcel
    }
    if (extension === 'pdf') {
      return IconFilePdf
    }
    if (['zip', 'rar', '7z', 'tar', 'gz'].includes(extension || '')) {
      return IconFileZip
    }
    if (['js', 'ts', 'html', 'css', 'java', 'py', 'php', 'cpp', 'c', 'h'].includes(extension || '')) {
      return IconCode
    }
    if (['txt', 'md', 'json', 'xml', 'log'].includes(extension || '')) {
      return IconFileText
    }
    return IconFile
  }

  // 处理预览
  const handlePreview = (file: any) => {
    previewFile.value = file
    previewVisible.value = true
  }

  // 关闭预览
  const closePreview = () => {
    previewVisible.value = false
    previewFile.value = null
  }

  return {
    previewVisible,
    previewFile,
    previewType,
    markdownContent,
    getFileType,
    getFileIcon,
    handlePreview,
    closePreview
  }
} 